package com.spring.nio.core.service.common;

import com.spring.nio.core.http.HttpResponse;
import com.spring.nio.core.http.model.RequestData;
import com.spring.nio.core.service.model.FileTask;
import com.spring.nio.core.service.model.TaskStatusEnum;
import com.spring.nio.core.service.upload.FileUploadRunnable;
import com.spring.nio.pool.WorkerThreadPool;
import com.spring.nio.util.LocalTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: YSFY
 * @date: 2021-04-17 21:52
 * @pacage_name: com.spring.nio.core.service.common
 * @class_name: FileService
 * @description: FileService
 */
@Slf4j
public class FileService {
    private static final FileService fileService = new FileService();
    private static final Map<String, FileTask> fileTaskMap = new ConcurrentHashMap<>();
    private FileService() {}

    public static FileService getFileService() {
        return fileService;
    }

    public static Map<String, FileTask> getFileTaskMap() {
        return fileTaskMap;
    }

    /**
     * 文件上传解析
     * @param requestData
     * @param socketChannel
     * */
    public void uploadHandler(RequestData requestData, final SocketChannel socketChannel) {
        // 1、校验文件是否存在
        String[] fileNames = requestData.getData().contains(",") ? requestData.getData().split(",") : new String[] { requestData.getData() } ;
        String clientFilePath = requestData.getClientUploadPath();
        Arrays.asList(fileNames).stream().forEach(fileName -> {

            this.checkFileNameLegitimacy(fileName, socketChannel);

            File uploadFile = new File(clientFilePath + fileName);
            if(uploadFile.exists() && uploadFile.isFile()) {
                // 2、异步上传文件
                FileTask fileTask = new FileTask();
                fileTask.setRequestData(requestData);
                fileTask.setTaskName(uploadFile.getName() + "_TASK");
                fileTask.setFile(uploadFile);
                fileTask.setServerRestorePath(requestData.getServerRestorePath());
                fileTask.setStatus(TaskStatusEnum.TASK_INIATIALIZE);
                fileTaskMap.putIfAbsent(fileTask.getTaskName(), fileTask);
                WorkerThreadPool.fileExecutorService.submit(new FileUploadRunnable(fileTask));
            } else {
                log.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] FileService | --> 待上传文件不存在或不是文件 文件名 = [{}]", uploadFile.getName());
            }
        });
    }

    /**
     * 校验文件名合法性
     * @param fileName
     * @param socketChannel
     * @return Boolean
     * */
    private Boolean checkFileNameLegitimacy(String fileName, final SocketChannel socketChannel) {
        if(StringUtils.equals("", fileName)) {
            log.info("[" + LocalTime.formatDate(LocalDateTime.now()) + "] FileService | --> 待上传文件名为空", fileName);
            return Boolean.FALSE;
        }

        return Boolean.TRUE;
    }

    /**
     * 发送http响应
     * @param message
     * @param socketChannel
     * */
    private void sendHttpResponse(String message, final SocketChannel socketChannel) {
        HttpResponse httpResponse = HttpResponse.getInstance();
    }

    /**
     * 文件下载处理
     * @param requestData
     * */
    public void downloadHandler(RequestData requestData) {

    }
}
